﻿using Blog.Core.Domain.Model;
using Blog.Core.DTO.ViewModel.From;
using Blog.Core.IRepositories;
using Blog.Core.IServices;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using AutoMapper;
using Blog.Core.DTO;
using Blog.Core.DTO.ViewModel;

namespace Blog.Core.Services
{
    public class FromService : BaseService<FromInfo>, IFromService
    {
        private readonly IFromRepository _fromRepository;
        private readonly IMapper mapper;
        private readonly IUnOfWork _unofWork;
        public FromService(IUnOfWork unOfWork, IFromRepository fromRepository, IMapper mapper) : base(fromRepository, unOfWork)
        {
            _fromRepository = fromRepository;
            this.mapper = mapper;
            _unofWork = unOfWork;
        }

        public async Task<ResponseResultDTO<List<FromInfo>>> GetFromList(string? name, int pageindex = 1, int pagesize = 10)
        {
            //统一返回值
            ResponseResultDTO<List<FromInfo>> result = new ResponseResultDTO<List<FromInfo>>();
            
            if (string.IsNullOrEmpty(name))
            {
                result.Code = ResultStatusCode.PARAMSERROR;
                result.Message = "无效参数";
                return result;
            }
            var list = await _fromRepository.GetAll();
            //list = list.Where(x => x.CreateName == name && x.Delete == 0).ToList();
            //返回成功的信息
            result.Code = ResultStatusCode.SUCCESS;
            //result.Data.RecordCount = list.Count();
            //result.Data.Plist = list;//.OrderBy(x => x.Id).Skip((pageindex - 1) * pagesize).Take(pagesize).ToList();
            result.Data = list;
            result.Message = "请求成功";
            return result;
        }

        public async Task<int> InsertFrom(RequestFromDTO model)
        {
            //AutoMapper映射为实体类
            FromInfo entity = mapper.Map<FromInfo>(model);
            //创建时间为当前时间
            entity.CreateTime = DateTime.Now.ToLocalTime();
            entity.CreateName = model.Name;
            //进行添加操作
            await _fromRepository.Add(entity);
            //保存到数据库的操作
            await _unofWork.SaveChanges();
            return 1;
        }
        public async Task<int> UpdateFrom(RequestFromDTO model)
        {
            //AutoMapper映射为实体类
            FromInfo entity = mapper.Map<FromInfo>(model);
            var t = await _fromRepository.GetById(model.Id);
            //创建时间为当前时间
            entity.CreateTime = t.CreateTime;
            entity.CreateName = t.CreateName;
            entity.UpdateTime=DateTime.Now.ToLocalTime();
            entity.UpdateName=model.Name;
            //进行添加操作
            _fromRepository.Update(entity);
            //保存到数据库的操作
            await _unofWork.SaveChanges();
            return 1;
        }
    }
}
